package thread;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

// 自定义线程池
class MyThreadPool {
    private Runnable run = new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Runnable task = queue.take();
                    task.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };

    // queue 是存储需要任务的
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private List<Thread> threads = new LinkedList<>();
    private int maxSize;

    public MyThreadPool(int coreSize, int maxSize) {
        this.maxSize = maxSize;
        for (int i = 0; i < coreSize; i++) {
            // 消费者
            Thread t = new Thread(run);
            // 开启
            t.start();
            threads.add(t);
        }
    }

    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);

        // 判断是否要添加线程
        if (queue.size() >= 500 && threads.size() < maxSize) {
            // 添加
            Thread t = new Thread(run);
            t.start();
            threads.add(t);
        }
    }
}

public class Demo35 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(4, 5);
        for (int i = 0; i < 10000; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println("hello " + id + " thread:" + Thread.currentThread().getName());
            });
        }
    }
}
